package com.yvan.serverless.jdbc.util;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.yvan.platform.StringUtils;
import com.yvan.serverless.jdbc.DaoParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DaoExecuterUpdateUtils {

    public static String getUpdateAnySql(String tableName, Map<String, Object> sets, Map<String, Object> wheres) {
        if (StringUtils.isBlank(tableName)) {
            throw new RuntimeException("TableName cannot be empty");
        }
        if (sets == null || sets.size() <= 0) {
            throw new RuntimeException("Sets cannot be empty");
        }
        if (wheres == null || wheres.size() <= 0) {
            throw new RuntimeException("Wheres cannot be empty");
        }
        List<String> setFieldList = new ArrayList<>();
        List<String> whereList = new ArrayList<>();
        for (String key : sets.keySet()) {
            setFieldList.add(key + "=?");
        }
        for (String key : wheres.keySet()) {
            whereList.add(key + "=?");
        }
        String sql = "update " + tableName + " set " + Joiner.on(",").join(setFieldList) + " where " + Joiner.on(" and ").join(whereList);
        return sql;
    }

    public static List<DaoParam> getUpdateAnyParams(Map<String, Object> sets, Map<String, Object> wheres) {
        List<DaoParam> values = Lists.newArrayList();
        List<DaoParam> setValueList = new ArrayList<>();
        List<DaoParam> whereList = new ArrayList<>();
        for (String key : sets.keySet()) {
            DaoParam param = new DaoParam(key, sets.get(key));
            setValueList.add(param);
        }
        for (String key : wheres.keySet()) {
            DaoParam param = new DaoParam(key, wheres.get(key));
            whereList.add(param);
        }
        values.addAll(setValueList);
        values.addAll(whereList);
        return values;
    }


}
